package com.linghui.videoplus.ipai;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

import com.linghui.videoplus.ipai.activity.BaseActivity;
import com.linghui.videoplus.ipai.activity.BrowserActivity;
import com.linghui.videoplus.ipai.activity.InitActivity;
import com.linghui.videoplus.ipai.api.Preferences;
import com.linghui.videoplus.ipai.bean.AccountBean;
import com.linghui.videoplus.ipai.bean.SinaAccessBean;
import com.linghui.videoplus.ipai.utils.ImageCache;

public class VideoPlusApplication extends Application {

	/** SDCAR **/
	public static String sdcardRoot = Environment.getExternalStorageDirectory()
			.getAbsolutePath();
	/** 视频保存目录 **/
	public static String videoRoot = sdcardRoot + "/videoplus/video/";
	/** 数据保存目录 **/
	public static String dataRoot = sdcardRoot + "/videoplus/data/";
	/** 图片缓存目录 **/
	public static String imageCacheRoot = sdcardRoot
			+ "/videoplus/data/imageCache/";
	/** 昵称保存文件 **/
	public static String nickNameFile = dataRoot + "NickNameSetting.json";
	/** 视频信息文件 **/
	public static String videoFile = dataRoot + "Video.json";

	public static List<Activity> sAllActivity = new LinkedList<Activity>();
	public static int LAST_FROM_CODE=1000;
	public static Object obj=new Object() ;
	
	public static int IMAGE_WIDTH = 100;
	public static int IMAGE_HEIGHT = 150;

	private static ImageCache mImageCache = new ImageCache();
	
	
	
	public static boolean isLogin(Context mContext){
		boolean flag=false;
		AccountBean accountBean=Preferences.getKanKanAccessBean(mContext);
		if(accountBean!=null){
			flag=true;
			return flag;
		}
		SinaAccessBean sinaBean=Preferences.getSinaAccessBean(mContext);
		if(sinaBean!=null){
			flag=true;
			return flag;
		}
		return flag;
	}


	public static String getUrlIndex(Activity mActivity){
		String urlIndex=mActivity.getResources().getString(R.string.url_index)+
			"?client=1&editor="
			+Preferences.getLocalUid(mActivity);
		return urlIndex;
	}
	public static String getUrlList(Activity mActivity){
		String urlAuthor=mActivity.getResources().getString(R.string.url_home) +
				"?type=1&keyword="
			+Preferences.getLocalUid(mActivity);
		return urlAuthor;
	}
	public static String getUrlVer(Activity mActivity){
		String urlVer=mActivity.getResources().getString(R.string.url_ver) ;
		return urlVer; 
	}
	
	
	/**
	 * 判断昵称配置文件是否存在
	 * 
	 * @return
	 */
	public static boolean isExistNickNameFile() {
		File f = new File(nickNameFile);
		if (f.exists()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 判断SD卡是否可用
	 */
	public static boolean isSDCardEnable() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}
	
	
	/**
	 * 获取SD卡空间大小
	 * @return
	 */
	public static long isAvaiableSpace() {
		long availableSpare=0;
		if(isSDCardEnable()){
		    String sdcard = Environment.getExternalStorageDirectory().getPath();
            StatFs statFs = new StatFs(sdcard);
            long blockSize = statFs.getBlockSize();
            long blocks = statFs.getAvailableBlocks();
            availableSpare = (blocks * blockSize);
		}
		return availableSpare;
	 }
	
	
	/**
	 * 判断 网络
	 * 
	 * @param context
	 * @return
	 */
	public static boolean checkNetWorkStatus(Context context) {
		boolean result = false;
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netinfo = cm.getActiveNetworkInfo();
		if (netinfo != null && netinfo.isConnected()) {
			if (netinfo.getState() == NetworkInfo.State.CONNECTED) {
				result = true;
			} else {
				result = false;
			}
		}
		return result;
	}

	/**
	 * 判断屏幕方向
	 * @param activity
	 * @return
	 */
	public static int getScreenOrient(Activity mActivity) {
	    int t = mActivity.getResources().getConfiguration().orientation ;  
	     if(t == Configuration.ORIENTATION_LANDSCAPE){  
	        Log.i("33333", "当前手机处于横屏"); 
	     	return 0;
	     } else if(t ==Configuration.ORIENTATION_PORTRAIT){  
	         Log.i("33333", "当前手机处于竖屏");  
	         return 1;
	     }  
	     return Configuration.ORIENTATION_LANDSCAPE;
	}

	/**
	 * 判断系统版本
	 * 
	 * @return
	 */
	public static int getAndroidSDKVersion() {
		int version = 0;
		try {
			version = Integer.valueOf(android.os.Build.VERSION.SDK);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return version;
	}

	/**
	 * 获取设备ID
	 * 
	 * @param context
	 * @return
	 */
	public static String getDeviceUUID(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);//
		String tmDevice, tmSerial, androidId;
		tmDevice = "" + tm.getDeviceId();
		tmSerial = "" + tm.getSimSerialNumber();
		androidId = ""
				+ android.provider.Settings.Secure.getString(
						context.getContentResolver(),
						android.provider.Settings.Secure.ANDROID_ID);
		UUID deviceUuid = new UUID(androidId.hashCode(),
				((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
		String uniqueId = deviceUuid.toString();
		return uniqueId;
	}
	
	
	

	/**
	 * 退出客户端
	 * 
	 * @param context
	 */
	public static void exitApplication(final BaseActivity context) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage("您确定退出程序吗?")
				.setTitle("提示")
				.setCancelable(false)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						CookieSyncManager.createInstance(context);
						CookieManager.getInstance().removeAllCookie();
						for (Activity activity : sAllActivity) {
							activity.finish();
						}
						sAllActivity.clear();
						android.os.Process.killProcess(android.os.Process
								.myPid());
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}
	/**
	 * 版本更新消息对话框
	 * @param context
	 * @param message
	 * @param exit true 强制， false 非强制
	 */
	public static void updateApplicationDialog(final BaseActivity mActivity,
			final String message, final boolean exit,final String url) {
		AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
		String title = "升级提示";
		String yes = "升级";
		String cancel = "取消";
		if (exit) {
			builder.setMessage(message).setTitle(title).setCancelable(false)
			.setPositiveButton(yes, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					Uri uri = Uri.parse(url);
					Intent it = new Intent(Intent.ACTION_VIEW, uri);
					mActivity.startActivity(it);
					mActivity.finish();				}
			});
		} else {
			builder.setMessage(message).setTitle(title).setCancelable(false).
			setPositiveButton(yes, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						Uri uri = Uri.parse(url);
						Intent it = new Intent(Intent.ACTION_VIEW, uri);
						mActivity.startActivity(it);
						mActivity.finish();
					}
				}).setNegativeButton(cancel, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						Intent intent=null;
						if (VideoPlusApplication.isExistNickNameFile()) {
							intent = new Intent(mActivity,BrowserActivity.class);
							intent = new Intent(mActivity,BrowserActivity.class);
							intent.putExtra("url", VideoPlusApplication.getUrlIndex(mActivity));
							intent.putExtra(mActivity.FROM_CODE_KEY, mActivity.REQUEST_CODE_INIT);
							intent.putExtra(mActivity.TO_CODE_KEY, mActivity.REQUEST_CODE_DEFAULT);
						} else {
							intent = new Intent(mActivity,InitActivity.class);
						}
						mActivity.startActivity(intent);
						mActivity.overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
						mActivity.finish();
					}
				});
		}
		AlertDialog alert = builder.create();
		alert.show();
	}
	
}
